package com.back_end.Reflection;

import com.TestDemo.TestBean;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DynamicCreateObject {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        // 获得class对象
        Class cc = Class.forName("com.TestDemo.TestBean");

        // 构造一个对象
//        User o = (User) cc.newInstance(); // 本质是调用类的无参构造器
        // 通过构造器创建对象
        Constructor constructor = cc.getConstructor(String.class,int.class);

        Constructor constructor1 = cc.getConstructor(null);

        TestBean o = (TestBean)constructor1.newInstance();
        System.out.println(o.toString());



        TestBean zjz = (TestBean)constructor.newInstance("zjz", 18);
        System.out.println(zjz.toString());


        TestBean zjz1 = (TestBean)cc.newInstance();
        Method setName = cc.getMethod("setName", String.class);

        // invoke:激活的意思
        // (对象，"方法的值")
        setName.invoke(zjz1,"zhangjzm");
        System.out.println("------" + zjz1.getName());

        // 通过反射操作属性
        TestBean zjz2 = (TestBean)cc.newInstance();
        Field name = cc.getDeclaredField("name");



        // 不能直接操作私有属性，关闭程序的安全检测
        name.setAccessible(true);

        name.set(zjz2,"zzzzz");
        System.out.println(zjz2.getName());

    }
}
